package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/*
* 全局异常处理器
* */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {


    /*
    * 异常处理方法
    * */
    @ExceptionHandler
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){ //如果控制台出现此类语句，说明添加的员工信息已存在，出现异常
            String[] split = ex.getMessage().split(" ");//split(" ")中一个空字符代表一个语句字符块如:Duplicate是一个语句字符块
            String msg = split[2] + "已存在";
            return Result.error(msg);
        }
        return Result.error("未知错误");
    }

    /*
     * 异常处理方法
     * */
    @ExceptionHandler(CustomException.class)//捕获自己的异常
    public Result<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return Result.error(ex.getMessage());
    }


}
